package pri.syl.xiaowu.websocket.core.container;

import com.google.common.collect.Maps;
import pri.syl.xiaowu.websocket.core.exception.WebsocketException;
import pri.syl.xiaowu.websocket.core.factory.UriFactory;
import pri.syl.xiaowu.websocket.core.template.WebsocketRouteTemplate;

import java.util.Map;

/**
 * @Author YunLong
 * @Date 2021/7/18 17:47
 * @Description 路由容器, 根据路由保存webSocket模板
 **/
public class WebsocketRouteContainer {
    private static final Map<String, WebsocketRouteTemplate> ROUTE_TEMPLATE = Maps.newConcurrentMap();
    private static final Map<String, WebsocketRouteTemplate> VARIABLE_ROUTE_TEMPLATE = Maps.newConcurrentMap();

    private WebsocketRouteContainer() {
    }

    /**
     * 存入WebsocketRouteTemplate
     *
     * @param route
     * @param websocketRouteTemplate
     * @return void
     * @apiNote [附加描述]
     * @author YunLong
     * @date 2021/7/19 9:15
     */
    public static void putWebsocketRouteTemplate(String route, WebsocketRouteTemplate websocketRouteTemplate) {
        boolean isVariable = UriFactory.containVariable(route);
        if (isVariable) {
            VARIABLE_ROUTE_TEMPLATE.put(route, websocketRouteTemplate);
        } else {
            ROUTE_TEMPLATE.put(route, websocketRouteTemplate);
        }
    }

    /**
     * 获取容器中webSocketTemplate
     *
     * @param requestUri
     * @return com.ruiruan.websocket.core.template.WebsocketRouteTemplate
     * @apiNote [附加描述]
     * @author YunLong
     * @date 2021/7/19 9:17
     */
    public static WebsocketRouteTemplate getWebsocketRouteTemplate(String requestUri) throws WebsocketException {
        WebsocketRouteTemplate websocketRouteTemplate = ROUTE_TEMPLATE.get(requestUri);
        if (null != websocketRouteTemplate) {
            return websocketRouteTemplate;
        }
        for (Map.Entry<String, WebsocketRouteTemplate> entry : VARIABLE_ROUTE_TEMPLATE.entrySet()) {
            if (UriFactory.isMatch(entry.getKey(), requestUri)) {
                return entry.getValue();
            }
        }
        throw new WebsocketException("unMatch RequestUri:" + requestUri);
    }
}
